<template>
  <div>
    <el-card class="box-card">
      <h2>新增用户</h2>
      <el-form :model="userForm" label-width="120px">
        <el-form-item label="用户名：">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码：">
          <el-input type="password" v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：">
          <el-input type="password" v-model="userForm.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
             <el-button @click="resetForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
    };
  },
  methods: {
    submitForm() {
      if (this.userForm.password !== this.userForm.confirmPassword) {
        this.$message.error('密码和确认密码不一致！');
        return;
      }

      const params = new URLSearchParams();
      params.append('username', this.userForm.username);
      params.append('email', this.userForm.email);
      params.append('password', this.userForm.password);
      params.append('confirmPassword', this.userForm.confirmPassword);

      this.axios.post('/api/user/add', params)
          .then(response => {
            this.$message({
              message: '用户创建成功',
              type: 'success'
            });
            this.$router.push('/list_user');
          })
          .catch(error => {
            console.error('Error creating user:', error);
            this.$message.error('用户创建失败');
          });
    },
    resetForm() {
             // 重置表单
             this.userForm = {
                 username: '',
                       email: '',
                       password: '',
                       confirmPassword: ''
             };
           }
  }
};
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 600px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
